package com.ffsky.litepack.task;

import com.ffsky.litepack.util.StringCompat;
import com.ffsky.logger.L;

import java.util.concurrent.LinkedBlockingQueue;

/**
 *
 * 队列线程,先进先出执行
 *
 */
final class QueueTask extends Thread {

    private static int mThreadInitNumber = 0;
    private String TAG = "QueueTask";
    private volatile boolean running = false;
    private LinkedBlockingQueue<Task> queue = new LinkedBlockingQueue<Task>();
    public QueueTask() {
        mThreadInitNumber++;
        setName(StringCompat.string("SKY-QUEUE-",String.valueOf(mThreadInitNumber)));
    }
    public boolean isRunning(){
        return running;
    }
    public void quit() {
        running = false;
        try{
            //向当前调用者线程发出中断信号
            interrupt();
        }catch (Exception exception){

        }
    }

    public void postTask(Task _task) {
        L.i(TAG,"postTask->",_task.getClass().getSimpleName());
        queue.add(_task);
    }
    public void clear(){
        queue.clear();
    }

    @Override
    public synchronized void run() {
        running = true;
        L.i(TAG, "+++");
        while (running) {
            L.i(TAG, "run task.....");
            try {
                Task mTask = queue.take();
                mTask.runTask();
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.gc();
        }
        L.i(TAG, "---");
    }
}
